﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using BLL;
using Model;
using System.Data;
using System.Reflection;

namespace OA.Controllers
{
    public class SystemNodeController : Controller
    {
        //
        // GET: /SystemNode/

        public ActionResult Index()
        {
            return View();
        }
        public ActionResult SystemNode()
        {
            operatorInfo OI = new operatorInfo();
            operatorInfoManager OPManager = new operatorInfoManager();
            List<operatorInfo> list = OPManager.GetAll().ToList();
            List<SelectListItem> select = new List<SelectListItem>();
            select.Add(new SelectListItem{ Text="所有操作员", Value="0", Selected=true});
            for(int i=0; i<list.Count();i++)
            {
                select.Add(new SelectListItem { Text=list[i].username , Value=list[i].id.ToString() });
            }
            ViewData["operator"] = select;
            return View();
        }
        //加载数据
        public ActionResult Load( FormCollection fc)
        {
            usersystemnode UM = new usersystemnode();
            usersystemnodeManager UMManager = new usersystemnodeManager();
            string expiresDate = fc["expiresDate"];
            string expiresDate2 = fc["expiresDate2"];
            string opeator = fc["opeator"];
            bool select =Convert.ToBoolean(fc["select"]);
            int pageSize = Convert.ToInt32(fc["pageSize"]);
            StringBuilder sb = new StringBuilder();
            List<usersystemnode> listAll = null;
            if (select)
            { 
                listAll = UMManager.GetByTime(expiresDate,expiresDate2,opeator).ToList();
                if (listAll.Count() > 0)
                {
                    for (int i = 0; i < listAll.Count(); i++)
                    {
                        if (i < pageSize)
                        {
                            sb.Append("<tr onmouseover=\"this.style.backgroundColor='#BCD2EE';cursor='default'\" onmouseout=\"this.style.backgroundColor='white'\">");
                            sb.Append("<td>" + listAll[i].id + "</th>");
                            sb.Append("<td>" + listAll[i].username + "</td>");
                            sb.Append("<td>" + listAll[i].loginTime + "</td>");
                            sb.Append("<td>" + listAll[i].leaveTime + "</td>");
                            sb.Append("</tr>");
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
            else
            {
                listAll = UMManager.GetAll().ToList();
                for (int i = 0; i < listAll.Count(); i++)
                {
                    if (i < pageSize)
                    {
                        sb.Append("<tr onmouseover=\"this.style.backgroundColor='#BCD2EE';cursor='default'\" onmouseout=\"this.style.backgroundColor='white'\">");
                        sb.Append("<td>" + listAll[i].id + "</td>");
                        sb.Append("<td>" + listAll[i].username + "</td>");
                        sb.Append("<td>" + listAll[i].loginTime + "</td>");
                        sb.Append("<td>" + listAll[i].leaveTime + "</td>");
                        sb.Append("</tr>");
                    }
                    else
                    {
                        break;
                    }
                }
            }
            return Content(sb.ToString());
        }
         //实现分页
        public ActionResult newPage(FormCollection fc)
        {
            int pageNum = Convert.ToInt32(fc["pageNum"]);
            int pageSize = Convert.ToInt32(fc["pageSize"]);
            int maxPage = pageNum * pageSize - 1;
            int minPage = maxPage - pageSize + 1;
            string expiresDate = fc["expiresDate"];
            string expiresDate2 = fc["expiresDate2"];
            string opeator = fc["opeator"];
            bool select = Convert.ToBoolean(fc["select"]);
            usersystemnode UM = new usersystemnode();
            usersystemnodeManager UMManager = new usersystemnodeManager();

            StringBuilder sb = new StringBuilder();
             List<usersystemnode> listAll = null;
             if (select)
             {
                 listAll = UMManager.GetByTime(expiresDate, expiresDate2, opeator).ToList();
                 if (listAll.Count() > 0)
                 {
                     for (int i = minPage; i <= maxPage; i++)
                    {
                        try
                        {
                             sb.Append("<tr onmouseover=\"this.style.backgroundColor='#BCD2EE';cursor='default'\" onmouseout=\"this.style.backgroundColor='white'\">");
                             sb.Append("<td>" + listAll[i].id + "</td>");
                             sb.Append("<td>" + listAll[i].username + "</td>");
                             sb.Append("<td>" + listAll[i].loginTime + "</td>");
                             sb.Append("<td>" + listAll[i].leaveTime + "</td>");
                             sb.Append("</tr>");
                        }

                        catch
                        {
                            break;
                        }

                    }
                 }
             }
             else
             {
                  listAll = UMManager.GetAll().ToList();
                 for (int i = minPage; i <= maxPage; i++)
                 {
                     try
                     {
                         sb.Append("<tr onmouseover=\"this.style.backgroundColor='#BCD2EE';cursor='default'\" onmouseout=\"this.style.backgroundColor='white'\">");
                         sb.Append("<td>" + listAll[i].id + "</td>");
                         sb.Append("<td>" + listAll[i].username + "</td>");
                         sb.Append("<td>" + listAll[i].loginTime + "</td>");
                         sb.Append("<td>" + listAll[i].leaveTime + "</td>");
                         sb.Append("</tr>");
                     }
                     catch
                     {
                         break;
                     }
                 }
             }
            return Content(sb.ToString());
        }

        //最大页数
        public ActionResult Data_Load_maxPage(FormCollection fc)
        {
            usersystemnode UM = new usersystemnode();
            usersystemnodeManager UMManager = new usersystemnodeManager();

            int pageSize = Convert.ToInt32(fc["pageSize"]);
            string expiresDate = fc["expiresDate"];
            string expiresDate2 = fc["expiresDate2"];
            string opeator = fc["opeator"];
            bool select = Convert.ToBoolean(fc["select"]);
            int count = 0;
             List<usersystemnode> listAll = null;
             if (select)
             {
                 listAll = UMManager.GetByTime(expiresDate, expiresDate2, opeator).ToList();
                 if (listAll.Count() > 0)
                 {
                      count = listAll.Count();
                 }
             }
             else
             {
                 listAll = UMManager.GetAll().ToList();
                  count = listAll.Count();
             }
            string oop = Math.Ceiling((double)count / pageSize).ToString();
            return Content(oop);
        }

        //删除全部日志
        public ActionResult delLog()
        {
            usersystemnodeManager UMManager = new usersystemnodeManager();
            if (UMManager.delLog())
            {
                return Content("删除成功");
            }
            else
            {
                return Content("删除失败");
            }
        }

        //导出表数据
        public ActionResult LogToExcel(FormCollection fc)
        {
            usersystemnodeManager UMManager = new usersystemnodeManager();
            DataTable dt = new DataTable();
            List<usersystemnode>  listAll = UMManager.GetAll().ToList();
            dt = LINQToDataTable<usersystemnode>(listAll);
            string fileName = "log" + DateTime.Now.ToShortDateString().Replace("_", "-") + ".xls";
            CreateExcel(dt, fileName);
            return View();

        }
        public void CreateExcel(DataTable dt, string fileName)
        {
            HttpResponse resp = System.Web.HttpContext.Current.Response;
            resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            resp.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
            string colHeaders = "", ls_item = "";
            ////定义表对象与行对象，同时用DataSet对其值进行初始化
            //DataTable dt = ds.Tables[0];
            DataRow[] myRow = dt.Select();//可以类似dt.Select("id>10")之形式达到数据筛选目的
            int i = 0;
            int cl = dt.Columns.Count;

            //取得数据表各列标题，各标题之间以t分割，最后一个列标题后加回车符
            for (i = 0; i < cl; i++)
            {
                if (i == (cl - 1))//最后一列，加n
                {
                    colHeaders += dt.Columns[i].Caption.ToString() + "\n";
                }
                else
                {
                    colHeaders += dt.Columns[i].Caption.ToString() + "\t";
                }
            }
            resp.Write(colHeaders);
            //向HTTP输出流中写入取得的数据信息
            //逐行处理数据 
            foreach (DataRow row in myRow)
            {
                //当前行数据写入HTTP输出流，并且置空ls_item以便下行数据   
                for (i = 0; i < cl; i++)
                {
                    if (i == (cl - 1))//最后一列，加n
                    {
                        ls_item += row[i].ToString() + "\n";
                    }
                    else
                    {
                        ls_item += row[i].ToString() + "\t";
                    }
                }
                resp.Write(ls_item);
                ls_item = "";
            }
            resp.End();

        }
        //将泛型转化成dataTable类型
        public DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
        {   //定义要返回的DataTable对象
            DataTable dtReturn = new DataTable();
            // 保存列集合的属性信息数组
            PropertyInfo[] oProps = null;
            if (varlist == null) return dtReturn;//安全性检查
            //循环遍历集合，使用反射获取类型的属性信息
            foreach (T rec in varlist)
            {
                //使用反射获取T类型的属性信息，返回一个PropertyInfo类型的集合
                if (oProps == null)
                {
                    oProps = ((Type)rec.GetType()).GetProperties();
                    //循环PropertyInfo数组
                    foreach (PropertyInfo pi in oProps)
                    {
                        Type colType = pi.PropertyType;//得到属性的类型
                        //如果属性为泛型类型
                        if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()
                        == typeof(Nullable<>)))
                        {   //获取泛型类型的参数
                            colType = colType.GetGenericArguments()[0];
                        }
                        //将类型的属性名称与属性类型作为DataTable的列数据
                        if (pi.Name == "id")
                        {
                            dtReturn.Columns.Add(new DataColumn("序列号", colType));
                        }
                        if (pi.Name == "username")
                        {
                            dtReturn.Columns.Add(new DataColumn("用户名", colType));
                        }
                        if (pi.Name == "loginTime")
                        {
                            dtReturn.Columns.Add(new DataColumn("登陆时间", colType));
                        }
                        if (pi.Name == "leaveTime")
                        {
                            dtReturn.Columns.Add(new DataColumn("离开时间", colType));
                        }
                        
                    }
                }
                //新建一个用于添加到DataTable中的DataRow对象
                DataRow dr = dtReturn.NewRow();
                //循环遍历属性集合
                foreach (PropertyInfo pi in oProps)
                {   //为DataRow中的指定列赋值

                    if (pi.Name == "id")
                    {
                        dr["序列号"] = pi.GetValue(rec, null) == null ?
                              DBNull.Value : pi.GetValue(rec, null);
                    }
                    if (pi.Name == "username")
                    {
                        dr["用户名"] = pi.GetValue(rec, null) == null ?
                              DBNull.Value : pi.GetValue(rec, null);
                    }
                    if (pi.Name == "loginTime")
                    {
                        dr["登陆时间"] = pi.GetValue(rec, null) == null ?
                              DBNull.Value : pi.GetValue(rec, null);
                    }
                    if (pi.Name == "leaveTime")
                    {
                        dr["离开时间"] = pi.GetValue(rec, null) == null ?
                              DBNull.Value : pi.GetValue(rec, null);
                    }
                   
                }
                //将具有结果值的DataRow添加到DataTable集合中
                dtReturn.Rows.Add(dr);
            }
            return dtReturn;//返回DataTable对象
        }
    }
}
